package com.efounder.agency.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import com.efounder.activity.AbActivity;
import com.efounder.builder.base.data.EFDataSet;
import com.efounder.builder.base.data.EFRowSet;
import com.efounder.eai.EAI;
import com.efounder.eai.data.JParamObject;
import com.efounder.eai.data.JResponseObject;
import com.efounder.forwechat.BaseApp;
import com.efounder.ospmobilelib.R;
import com.efounder.util.GlobalMap;
import com.efounder.util.LoadingDataUtilBlack;
import com.efounder.view.titlebar.AbTitleBar;
import com.zhy.bean.TreeBean;
import com.zhy.tree.bean.TreeHelper;
import com.zhy.tree.bean.TreeListViewAdapter;
import com.zhy.tree.bean.TreeListViewAdapter.OnTreeNodeClickListener;
import com.zhy.tree.bean.TreeNode;
import com.zhy.tree_view.SimpleTreeAdapter;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;

public class DeptUserTreeActivity extends AbActivity implements OnClickListener {
    private static final String TAG = "DeptUserTreeActivity";
    private List<TreeBean> mDatas = new ArrayList<TreeBean>();
    private ListView mTree;
    private TreeListViewAdapter mAdapter;

    private String filter;

    private AbTitleBar mTitleBar;
    private String type;
    private String systemType;
    private LoadDataAsyncTask loadDataAsyncTask;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        BaseApp.actManager.putActivity(TAG, this);
        setAbContentView(R.layout.activity_dept_user_tree);
        mTree = (ListView) findViewById(R.id.id_tree);
        try {
            mAdapter = new SimpleTreeAdapter(mTree, this, mDatas, 10);
            mAdapter.setOnTreeNodeClickListener(new OnTreeNodeClickListener() {
                @Override
                public void onClick(AdapterView<?> parent, View view,
                                    TreeNode node, int position) {
                    boolean isUser = "user".equals(node.getAttrs().get(
                            "elementname"));// elementname=user
                    if ("group".equals(type)) {
                        isUser = true;
                    }
                    if (node.isLeaf()) {
                        if (isUser) {
                            if (node.isHasCheckBox()) {
                                boolean isChecked = !node.isChecked();
                                node.setChecked(isChecked);
                                Log.i("", "TreeNode-onClick------ischecked:"
                                        + isChecked);
                            }
                        } else {
                            if (loadDataAsyncTask != null) {
                                loadDataAsyncTask.cancel(true);
                            }
                            loadDataAsyncTask = new LoadDataAsyncTask(node,
                                    mAdapter);
                            loadDataAsyncTask.executeOnExecutor(Executors
                                    .newCachedThreadPool());
                        }
                    }
                    mAdapter.notifyDataSetChanged();
                    Log.i("",
                            "----------选中的所有节点(不包含叶子节点)："
                                    + TreeHelper
                                    .filterCheckedLeafNodes(mAdapter
                                            .getAllNodes()));
                }

            });

        } catch (Exception e) {
            e.printStackTrace();
        }
        mTree.setAdapter(mAdapter);

        initView();

        initDatas();
    }

    private void initView() {

        mTitleBar = this.getTitleBar();
        String title = getIntent().getStringExtra("title");
        mTitleBar.setTitleText(title);
        mTitleBar.setTitleTextColor(getResources().getColor(R.color.title_TextColor));
        mTitleBar.setLogo(R.drawable.ef_title_view_back);
        mTitleBar.setTitleBarBackground(R.color.title_Background);

        // 添加提交按钮
        Button selectButton = new Button(this);
        selectButton.setText("选择");
        selectButton.setTextSize(16);
        selectButton.setTextColor(Color.WHITE);
        selectButton.setBackgroundColor(Color.TRANSPARENT);
        mTitleBar.addRightView(selectButton);
        mTitleBar.setTitleBarGravity(Gravity.CENTER, Gravity.CENTER);
        mTitleBar.setLogoOnClickListener(this);
        selectButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                ArrayList<TreeNode> selectedNodes = (ArrayList<TreeNode>) TreeHelper
                        .filterCheckedLeafNodes(mAdapter.getAllNodes());
                if (selectedNodes == null || selectedNodes.size() == 0) {
                    Toast.makeText(DeptUserTreeActivity.this, "请选择人员",
                            Toast.LENGTH_LONG).show();
                } else {
                    Intent intent = new Intent();
                    // 把返回数据存入Intent
                    intent.putExtra("result", selectedNodes);
                    // 设置返回数据
                    setResult(RESULT_OK, intent);
                    // 关闭Activity
                    BaseApp.actManager.removeActivity(TAG);
                }

            }
        });

    }

    private void initDatas() {
        filter = getIntent().getStringExtra("filter");
        type = getIntent().getStringExtra("type");

        systemType = getIntent().getStringExtra("systemType");
        // systemType = "CONTRACT";
        // filter = "3509,24089";
        // 初始化数据时，parentID 传入 null，表示根节点
        if (loadDataAsyncTask != null) {
            loadDataAsyncTask.cancel(true);
        }
        loadDataAsyncTask = new LoadDataAsyncTask(null, mAdapter);
        loadDataAsyncTask.executeOnExecutor(Executors.newCachedThreadPool());
    }

    /**
     * 异步加载
     *
     * @author XinQing
     */
    private class LoadDataAsyncTask extends
            AsyncTask<String, Integer, List<TreeBean>> {

        private TreeNode parentNode;
        private TreeListViewAdapter treeListViewAdapter;

        /**
         * @param parentNode          parentNode == null 表示根节点
         * @param treeListViewAdapter
         */
        public LoadDataAsyncTask(TreeNode parentNode,
                                 TreeListViewAdapter treeListViewAdapter) {
            super();
            this.parentNode = parentNode;
            this.treeListViewAdapter = treeListViewAdapter;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // 加载dialog显示
            LoadingDataUtilBlack.show(DeptUserTreeActivity.this);
        }

        @Override
        protected List<TreeBean> doInBackground(String... params) {
            List<TreeBean> treeBeans;
            if (filter.contains("getDeptPersonByPerson")) {
                treeBeans = getUserData(parentNode == null ? filter
                        : parentNode.getId());
            }
            // else if (filter.contains("getsongbumenbanliperson")) {

            // }
            else {
                treeBeans = getDeptData(parentNode == null ? filter
                        : parentNode.getId());
            }
            return treeBeans;
        }

        @Override
        protected void onCancelled() {
            // TODO Auto-generated method stub
            super.onCancelled();
            LoadingDataUtilBlack.dismiss();
        }

        @Override
        protected void onPostExecute(List<TreeBean> treeBeans) {
            super.onPostExecute(treeBeans);

            LoadingDataUtilBlack.dismiss();

            if (treeBeans != null && treeBeans.size() > 0) {
                List<TreeNode> visibleNodes = TreeHelper.addChildNodesToTree(
                        treeListViewAdapter.getAllNodes(), parentNode,
                        treeBeans);
                treeListViewAdapter.setVisibleNodes(visibleNodes);
                if (parentNode == null) {
                    treeListViewAdapter.notifyDataSetChanged();
                } else {// 点击时调用，非初始化时调用
                    treeListViewAdapter.expandOrCollapse(visibleNodes
                            .indexOf(parentNode));
                }
            }
        }

        private List<TreeBean> getDeptData(String parentId) {
            List<TreeBean> treeBeans = null;
            // 创建PO
            JParamObject PO = JParamObject.Create();
            JResponseObject RO = null;
            String tokenConId = GlobalMap.getProperty(systemType
                    + "Id", "");

            PO.SetValueByParamName("WB_SYS_KEY", systemType);

            if ("FFS".equals(systemType)) {// 费用报销
                PO.SetValueByParamName(systemType + "_params_orgId", parentId);
                PO.SetValueByParamName(systemType + "_systemmethod",
                        "GetOrgListHandler");
            } else if ("CONTRACT".equals(systemType)) {// 合同
                PO.SetValueByParamName(systemType + "_params_departmentId",
                        parentId);
                PO.SetValueByParamName(systemType + "_systemmethod",
                        "GetOrgListResultHandler");
            } else {// OA(包含国勘)
                PO.SetValueByParamName(systemType + "_params_depId", parentId);
                PO.SetValueByParamName(systemType + "_systemmethod",
                        "GetOrgListHandler");
            }
            PO.SetValueByParamName(systemType + "_params_tokenIDFromMoblie",
                    tokenConId);

            try {
                // 连接服务器
                RO = EAI.DAL.SVR("ExternalInterfaceDataService", PO);
                treeBeans = getTreeBeans(RO);
                Log.i("", "------返回节点数量：" + treeBeans.size());
                if (treeBeans.size() == 0) {
                    treeBeans = getUserData(parentId);
                } else {
                    List<TreeBean> userTreeBean = getUserData(parentId);
                    if (userTreeBean != null) {
                        treeBeans.addAll(userTreeBean);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            return treeBeans;
        }

        private List<TreeBean> getUserData(String parentId) {
            List<TreeBean> treeBeans = null;
            // 创建PO
            JParamObject PO = JParamObject.Create();
            JResponseObject RO = null;
            String tokenConId = GlobalMap.getProperty(systemType
                    + "Id", "");

            PO.SetValueByParamName("WB_SYS_KEY", systemType);
            // PO.SetValueByParamName(systemType + "_params_depId", parentId);
            if ("FFS".equals(systemType)) {// 费用报销
                PO.SetValueByParamName(systemType + "_params_orgId", parentId);
            } else if ("CONTRACT".equals(systemType)) {// 合同管理
                PO.SetValueByParamName(systemType + "_params_departmentId",
                        parentId);
            } else {
                PO.SetValueByParamName(systemType + "_params_depId", parentId);
            }
            PO.SetValueByParamName(systemType + "_params_tokenIDFromMoblie",
                    tokenConId);

            PO.SetValueByParamName(systemType + "_systemmethod",
                    "GetUserListHandler");
            // PO.SetValueByParamName("OA_systemmethod", "GetOrgListHandler");

            try {
                // 连接服务器
                RO = EAI.DAL.SVR("ExternalInterfaceDataService", PO);
                treeBeans = getTreeBeans(RO);

            } catch (Exception e) {
                e.printStackTrace();
            }

            return treeBeans;
        }

        @SuppressWarnings("unchecked")
        private List<TreeBean> getTreeBeans(JResponseObject RO) {
            List<TreeBean> treeBeans = new ArrayList<TreeBean>();
            if (RO == null) {
                return treeBeans;
            }
            Map<String, Map<String, EFDataSet>> map = RO.getResponseMap();
            // 1 DataSet
            EFDataSet rootDataSet = (EFDataSet) map.get(systemType);
            List<EFRowSet> rowSets = rootDataSet.getRowSetArray();
            String elementname = "";
            if (rowSets != null) {
                elementname = rowSets.get(0).getString("elementname", "");
            }

            if (rowSets == null || rowSets.size() == 0
                    || "options".equals(elementname)
                    || "tabs".equals(elementname)) {
                return treeBeans;
            }
            for (EFRowSet efRowSet : rowSets) {

                Map<String, Object> attrMap = efRowSet.getAttriMap();
                Log.i("", "------- " + attrMap);
                String id = (String) attrMap.get("id");
                String parentId = (parentNode == null ? null : parentNode
                        .getId());
                // 对于送部门办理选项，需要加入选择框处理 yqs 2016.10.8
                // {name=中原油田（徐金莲）, haschildren=false, id=1^$^中原油田,
                // elementname=department, parentid=, elementtext=,
                // _Self_RowSet=}
                boolean isUser = "user".equals(attrMap.get("elementname"));
                boolean isDepartment = "department".equals(attrMap
                        .get("elementname"));
                String name = (String) (isUser ? attrMap.get("fullname")
                        : attrMap.get("name"));

                TreeBean treeBean = new TreeBean(id, parentId, name);
                if (!type.equals("group")) {
                    treeBean.setHasCheckBox(isUser);
                } else {
                    treeBean.setHasCheckBox(isDepartment);
                }

                treeBean.setAttrs(attrMap);
                treeBeans.add(treeBean);
            }

            return treeBeans;
        }

    }

    @Override
    public void onClick(View v) {

        int id = v.getId();
        if (id == R.id.button_back) {
            // this.finish();
            BaseApp.actManager.removeActivity(TAG);
        } else if (v == mTitleBar.getLogoView()) {
            BaseApp.actManager.removeActivity(TAG);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (loadDataAsyncTask != null) {
            loadDataAsyncTask.cancel(true);
            loadDataAsyncTask = null;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            BaseApp.actManager.removeActivity(TAG);
            return false;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }
}
